<template>
	<view>
		<!-- 加载中蒙版 -->
		<uni-transition mode-class="fade" :duration="500" :show="!dataLoaded" custom-class="vague-bg-9 mask-load">
		</uni-transition>
		<!-- #ifdef MP-WEIXIN -->
		<!-- 顶部导航 -->
		<view>
			<custom-navber :path="`/pages/user/myPage?usid=${circleDetail.user_id}`"
				:userGender="circleDetail.user_gender"
				:imgUrl="circleDetail.user_avatar|| 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
				:title="circleDetail.user_name || '匿名用户'"></custom-navber>
		</view>
		<!-- #endif -->
		<!-- 轮播 -->
		<view :style="{paddingTop:menuObject.top + menuObject.height + 8 +'px'}" class="w-100">
			<z-swiper ref="zSwiper" v-model="circleDetail.thumbnail" :options="options" @slideChange="onChange">
				<z-swiper-item v-for="(item,index) in circleDetail.thumbnail" :key="index">
					<image @click="previewImage(index)" class="w-100 image-height" :src="item" mode="aspectFill">
					</image>
				</z-swiper-item>
			</z-swiper>
		</view>
		<!-- 轮播图指示点 -->
		<view class="pos-rela w-100" style="height: 10rpx;">
			<sdp :resdata="circleDetail.thumbnail" :currentIndex="swiperIndex" class="my-sdp pos-abso"></sdp>
		</view>
		<view class="ping-30 bottom-index pos-rela">
			<image src="https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/bl.png"
				class="w-100 h-60 pos-abso img-min" />
			<view class="fw-600 fs-32">{{circleDetail.title || ''}}</view>
			<!-- <view class="fs-24 mt-20 col-b1">2-20 10:00</view> -->
			<view class="fs-30 mt-20">
				<mp-html :content="circleDetail.content"></mp-html>
			</view>
			<view v-if="circleDetail.activity_id"
				class="bac-col-fa flex-dir-row flex-x-bet ali-item-cen ping-10 br-20 mt-20">
				<view class="flex-dir-row ali-item-cen pr-10">
					<image class="br-10 image-activity" :src="circleDetail.activity_img[0].src" mode="aspectFill">
					</image>
					<view class="ml-10 flex-1 flex-dir-col">
						<view class="fs-28 text-element-1 ">{{circleDetail.activity_name}}</view>
						<view class="fs-24 col-b1 mt-5">{{circleDetail.sign_up_count}}人已报名活动</view>
					</view>
				</view>
				<view class="border-left fs-28 ping-0-20 whi-sp"
					@click="$NavigateTo(`/pages/detail/detail?id=${circleDetail.activity_id}`)">去报名</view>
			</view>
			<view class="fw-600 fs-30 mt-30">评论（{{commentList.length || 0}})</view>
			<view class="mt-20 pb-20">
				<view v-for="(item, index) in commentList" class="flex-dir-row ali-item-sta mb-30" :key="index">
					<!-- 头像 -->
					<qmy-gender-border @click="$NavigateTo(`/pages/user/myPage?usid=${item.user_id}`)"
						:gender="item.user_gender"
						:avatar="item.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
						:avatarWidth="70 + 'rpx'" :avatarHeight="70 + 'rpx'"></qmy-gender-border>
					<!-- <image @click="$NavigateTo(`/pages/user/myPage?usid=${item.user_id}`)" class="br-200 image-small"
						mode="aspectFill"
						:src="item.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'">
					</image> -->
					<view class="flex-1 flex-dir-col ml-20">
						<!-- 昵称 -->
						<view class="fs-28 col-87 text-element-1">{{ item.user_name  || '匿名用户'}}</view>
						<!-- 评论内容 -->
						<view class="fs-30 mt-5">
							<view>{{ item.comment_content }}</view>
							<view class="flex-dir-row flex-x-bet ali-item-cen col-b1 mt-5">
								<view class="flex-dir-row ali-item-cen">
									<view class="fs-26 col-b1">{{$timeFormat(item.create_date)}}</view>
									<view @click="reply(item)" class="fs-26 col-87 ml-10 fw-600">回复</view>
								</view>
								<view class="flex-dir-row ali-item-cen">
									<view @click="likeComment(item._id, 0)" class="iconfont fs-44"
										:class="item.like_user_id.includes(userInfo._id) ? 'col-00ba31 ic-nice' : 'col-b1 ic-nice-line'">
									</view>
									<view v-if="item.like_user_id.length" class="fs-30">{{ item.like_user_id.length }}
									</view>
								</view>
							</view>
						</view>
						<!-- 关联评论（折叠显示） -->
						<view v-if="item.new_reply_comment_info && item.new_reply_comment_info.length"
							class="fs-30 mt-20 bg-f6 p-20 br-10 overflow-h">
							<view
								:style="{height: (displayedReplies[item._id] || 1) * commentHeight + 'px', transition: 'height 0.3s ease-in-out'}"
								class="overflow-h">
								<view id="commentHeight" v-for="(its, i) in item.new_reply_comment_info"
									class="flex-dir-row ali-item-sta pb-20" :key="i">
									<qmy-gender-border @click="$NavigateTo(`/pages/user/myPage?usid=${its.user_id}`)" iconWidth="20rpx" iconHeight="20rpx" iconSize="16rpx" iconLineHeight="20rpx"
										:gender="its.reply_user_gender"
										:avatar="its.reply_user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
										:avatarWidth="55 + 'rpx'" :avatarHeight="55 + 'rpx'"></qmy-gender-border>


									<view class="flex-1 flex-dir-col ml-20">
										<view class="fs-26 col-87 text-element-1 flex-dir-row ali-item-cen">
											<text>{{its.reply_user_name || '匿名用户'}}</text>
											<view v-if="its.displayText" class="flex-dir-row ali-item-cen">
												<text
													class="iconfont ic-arrow_right_fat fs-34 mt-5 ml-5 mr-5 col-b1"></text>
												<text>{{its.displayText}}</text>
											</view>
										</view>
										<view class="fs-30 mt-5">
											<view>{{ its.comment_content }}</view>
											<view class="flex-dir-row flex-x-bet ali-item-cen col-b1 mt-5">
												<view class="flex-dir-row ali-item-cen">
													<view class="fs-26 col-b1">{{$timeFormat(its.create_date)}}</view>
													<view @click="reply(its,item)" class="fs-26 col-87 ml-10 fw-600">回复
													</view>
												</view>
												<view class="flex-dir-row ali-item-cen">
													<view @click="likeComment(its._id, 1)" class="iconfont fs-44"
														:class="its.reply_like_user_id.includes(userInfo._id) ? 'col-00ba31 ic-nice' : 'col-b1 ic-nice-line'">
													</view>
													<view v-if="its.reply_like_user_id.length" class="fs-30">
														{{ its.reply_like_user_id.length }}
													</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
							<!-- 展开/收起按钮 -->
							<view v-if="item.new_reply_comment_info.length > 1"
								class="fs-26 col-87 flex-dir-row ali-item-cen">
								<view v-if="(displayedReplies[item._id] || 1) < item.new_reply_comment_info.length"
									class="flex-dir-row ali-item-cen">
									<view @click="expandReply(item._id, item.new_reply_comment_info.length)">
										<text class="iconfont ic-hengxian1 mr-10"></text>
										<text
											v-if="displayedReplies[item._id]?displayedReplies[item._id] == 1 : !displayedReplies[item._id]">{{`展开${item.new_reply_comment_info.length - (displayedReplies[item._id] || 1)}条回复`}}</text>
										<text v-else class="fw-600">查看更多</text>
										<text class="iconfont ic-shang ml-5 fw-600"></text>
									</view>
									<view @click="retractReply(item._id)"
										v-if="displayedReplies[item._id]?displayedReplies[item._id] > 1 : displayedReplies[item._id]"
										class="ml-30">
										<text class="fw-600">收起</text>
										<text class="iconfont ic-xia fw-600"></text>
									</view>
								</view>
								<text v-else class="fw-600" @click="retractReply(item._id)">收起回复</text>
							</view>

						</view>

					</view>
				</view>
			</view>
		</view>
		<!-- 底部输入框，动态定位适配输入法高度 -->
		<view class="bor-top-f3 bac-col-f bac-col-f w-100 ping-20 fixed-bottom"
			:class="keyboardHeight == 0 ?'bottom-h':''" :style="{bottom:keyboardHeight+'px'}">
			<view class="flex-dir-row ali-item-cen flex-x-bet">
				<view class="bac-col-fa ping-10-20 br-10 input-container">
					<input class="fs-26 w-100 auto-blur input-style" type="text" @focus="focusChange" @blur="blurChange"
						:adjust-position="false" v-model="commentText" confirm-type="send"
						:placeholder="inputPlaceholder" @confirm="inputComment" :focus="inputFocus" />
				</view>
				<view @click="likeCircle" class="text-ali-c">
					<view class="iconfont fs-50"
						:class="circleDetail.like_user_id && circleDetail.like_user_id.includes(userInfo._id) ? 'col-00ba31 ic-nice' : 'ic-nice-line'">
					</view>
					<view class="fs-26">{{circleDetail.like_user_id && circleDetail.like_user_id.length}}</view>
				</view>
				<view @click="commentCircle" class="text-ali-c">
					<view class="iconfont ic-talk-line fs-50"></view>
					<view class="fs-26">{{commentList.length}}</view>
				</view>
				<!-- #ifdef MP-WEIXIN -->
				<button open-type="share" class="text-ali-c">
					<view class="iconfont ic-share-line fs-50 lh-50"></view>
					<view class="fs-26" style="line-height: 34rpx;">分享</view>
				</button>
				<!-- #endif -->
				<!-- #ifndef MP-WEIXIN -->
				<view @click="$Toast('H5暂不开放分享')" class="text-ali-c">
					<view class="iconfont ic-talk-line fs-50"></view>
					<view class="fs-26">{{commentList.length}}</view>
				</view>
				<!-- #endif -->
			</view>
		</view>
	</view>
</template>

<script>
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	import sdp from '@/components/swiper-dynamic-bullets/swiper-dynamic-bullets.vue';
	export default {
		components: {
			sdp
		},
		data() {
			return {
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: 0,
				// #endif
				options: {
					initialSlide: 0, //初始显示的图片下标
				},
				swiperIndex: 0, //轮播图下标
				commentText: '', //评论内容
				circleId: '', //圈子id
				circleDetail: {}, //圈子详情
				commentList: [], //评论列表
				replyCommentType: 0, //回复的评论类型，0表示评论圈子，1表示回复评论
				inputPlaceholder: '和大家一起聊聊吧...', //输入框提示
				inputFocus: false, //输入框是否聚焦
				replyCommentId: '', //回复的评论id
				showAllReply: {}, // 记录每个评论是否展开关联评论
				commentHeight: 0, // 存储获取到的高度
				displayedReplies: {}, // 每个 item 显示的评论数量
				keyboardHeight: 0, // 键盘高度
				dataLoaded: false, //数据加载完成
				superlativeId: '', //最高级评论id
			}
		},
		computed: {
			userInfo() {
				return store.userInfo //用户信息
			},
		},
		onLoad(e) {
			this.circleId = e.id;
			// 获取圈子详情
			this.getCircleDetail();
			//获取评论
			this.getComment();
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.dataLoaded = false; //数据加载完成
			// 获取圈子详情
			this.getCircleDetail();
			//获取评论
			this.getComment();
		},
		methods: {
			//图片预览
			previewImage(index) {
				uni.previewImage({
					urls: this.circleDetail.thumbnail,
					current: index
				});
			},
			//获取圈子详情
			getCircleDetail() {
				this.$Route('get-public-data').getCircleDetail(this.circleId).then((res) => {
					this.circleDetail = res.data[0];
					uni.stopPullDownRefresh();
					this.dataLoaded = true; //数据加载完成
				}).catch((err) => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						this.$NavigateBack();
					}, 1600);
				});
			},
			//获取评论
			getComment() {
				this.$Route('get-public-data').getCircleComment(this.circleId).then((res) => {
					this.commentList = res.data;
					this.commentList = this.commentListProcessed();
					this.$nextTick(() => {
						this.getCommentHeight();
					})
				}).catch((err) => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
				});
			},
			// 获取单条评论的高度
			getCommentHeight() {
				uni.createSelectorQuery()
					.select("#commentHeight")
					.boundingClientRect((res) => {
						if (res) {
							console.log("单条评论高度:", res.height);
							this.commentHeight = res.height;
						}
					})
					.exec();
			},

			// 展开/收起评论
			toggleReply(commentId, totalCount) {
				// 震动
				uni.vibrateShort();
				if (!this.displayedReplies[commentId]) {
					// 默认显示 1 条
					this.$set(this.displayedReplies, commentId, 1);
				}

				if (this.displayedReplies[commentId] < totalCount) {
					// 每次增加 10 条
					this.displayedReplies[commentId] = Math.min(this.displayedReplies[commentId] + 10, totalCount);
				} else {
					// 已经全部展开 -> 重新折叠回 1 条
					this.displayedReplies[commentId] = 1;
				}
			},
			//展开回复
			expandReply(commentId, totalCount) {
				this.toggleReply(commentId, totalCount);
			},
			//收起回复
			retractReply(commentId) {
				this.toggleReply(commentId);
			},
			//点赞圈子
			likeCircle(id) {
				this.$debounce(() => {
					// 震动
					uni.vibrateShort();
					// 点赞或取消点赞时先更新点赞状态点赞数，等待返回在确认是否复原
					this.circleDetail.like_user_id.includes(this.userInfo._id) ? this.circleDetail.like_user_id
						.splice(this
							.circleDetail.like_user_id
							.indexOf(this.userInfo._id), 1) : this.circleDetail.like_user_id.push(this.userInfo
							._id);
					this.$Route('add-private-data', true).likeCircle(this.circleDetail._id).then().catch((err) => {
						this.circleDetail.like_user_id.includes(this.userInfo._id) ? this.circleDetail
							.like_user_id
							.splice(this.circleDetail
								.like_user_id.indexOf(this.userInfo._id), 1) : this.circleDetail
							.like_user_id.push(
								this.userInfo._id);
						console.error('遇到错误:', err); // 打印错误信息
						let {
							code,
							msg
						} = this.$parseError(err); // 调用公共解析方法
						this.$Toast(msg);
						setTimeout(() => {
							if (code === 401) {
								this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
							}
						}, 1000);
					});
				}, 500, true, "likeCircle")
			},
			//轮播图
			onChange(swiper, index) {
				this.swiperIndex = index
			},
			//输入框
			inputComment() {
				if (this.replyCommentType == 1) {
					this.$Route('add-private-data').replyComment(this.circleId, this.replyCommentId, this.commentText, this
							.superlativeId)
						.then((res) => {
							this.$Toast('回复成功')
							this.resetInput();
							setTimeout(() => {
								this.getComment();
							}, 1000)
						}).catch((err) => {
							console.error('遇到错误:', err); // 打印错误信息
							let {
								code,
								msg
							} = this.$parseError(err); // 调用公共解析方法
							this.$Toast(msg);
							setTimeout(() => {
								if (code === 401) {
									this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
								}
							}, 1000);
						})
				} else {
					this.comment();
				}
			},
			// 输入框获取焦点触发
			focusChange(e) {
				this.keyboardHeight = e.detail.height;
			},
			// 输入框失去焦点触发
			blurChange() {
				this.keyboardHeight = 0;
				this.resetInput();
			},
			//恢复输入框
			resetInput() {
				this.replyCommentType = 0;
				this.commentText = '';
				this.inputPlaceholder = '和大家一起聊聊吧...';
				this.inputFocus = false
			},
			//评论
			comment() {
				this.$Route('add-private-data').commentCircle(this.circleId, this.commentText).then((res) => {
					this.$Toast('评论成功')
					this.resetInput();
					setTimeout(() => {
						this.getComment();
					}, 1000)
				}).catch((err) => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				})
			},
			// 点赞评论
			likeComment(id, type) {
				this.$debounce(() => {
					// 震动
					uni.vibrateShort();
					// 点赞或取消点赞时先更新点赞状态点赞数，等待返回在确认是否复原
					this.commentList.forEach(item => {
						if (type == 0) {
							if (item._id == id) {
								item.like_user_id.includes(this.userInfo._id) ? item.like_user_id.splice(
									item
									.like_user_id
									.indexOf(this.userInfo._id), 1) : item.like_user_id.push(this
									.userInfo._id);
							}
						} else {
							item.new_reply_comment_info.forEach(its => {
								if (its._id == id) {
									its.reply_like_user_id.includes(this.userInfo._id) ? its
										.reply_like_user_id
										.splice(its.reply_like_user_id
											.indexOf(this.userInfo._id), 1) : its
										.reply_like_user_id.push(this
											.userInfo._id);
								}
							})
						}
					})
					this.$Route('add-private-data', true).likeComment(id).then((res) => {}).catch((err) => {
						this.commentList.forEach(item => {
							if (type == 0) {
								if (item._id == id) {
									item.like_user_id.includes(this.userInfo._id) ? item
										.like_user_id.splice(
											item
											.like_user_id.indexOf(this.userInfo._id), 1) : item
										.like_user_id
										.push(
											this.userInfo._id);
								}
							} else {
								item.new_reply_comment_info.forEach(its => {
									if (its._id == id) {
										its.reply_like_user_id.includes(this.userInfo
												._id) ? its
											.reply_like_user_id.splice(its
												.reply_like_user_id
												.indexOf(this.userInfo._id), 1) : its
											.reply_like_user_id.push(this.userInfo._id);
									}
								})
							}
						})
						console.error('遇到错误:', err); // 打印错误信息
						let {
							code,
							msg
						} = this.$parseError(err); // 调用公共解析方法
						this.$Toast(msg);
						setTimeout(() => {
							if (code === 401) {
								this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
							}
						}, 1000);
					})
				}, 500, true, "likeComment")
			},
			// 回复评论
			reply(item, its) {
				this.superlativeId = its?._id || item._id;
				this.replyCommentId = item._id;
				this.inputPlaceholder = `回复@${item.user_name || item.reply_user_name || '匿名用户'}:`;
				this.replyCommentType = 1;
				this.inputFocus = true;
			},
			// 评论圈子
			commentCircle() {
				this.replyCommentId = '';
				this.inputPlaceholder = '和大家一起聊聊吧...';
				this.replyCommentType = 0;
				this.inputFocus = true;
			},
			commentListProcessed() {
				return this.commentList.map(comment => {
					// 1. 先筛选出 reply_comment_id 不等于主评论 _id 的数据
					let replyList = comment.new_reply_comment_info.map(reply => ({
						...reply,
						displayText: ''
					}));
					// 2. 从关联评论里找到匹配的 reply_comment_id 并填充 displayText 
					replyList.forEach(reply => {
						if (reply.reply_comment_id !== comment._id) {
							let repliedTo = replyList.find(item => item._id === reply.reply_comment_id);
							if (repliedTo) {
								reply.displayText =
									`${repliedTo.reply_user_name || '匿名用户'}`;
							}
						}
					});

					return {
						...comment,
						new_reply_comment_info: replyList
					};
				});
			}
		}
	}
</script>

<style lang="scss">
	.my-sdp {
		left: 50%;
		transform: translate(-50%, 0%);
	}

	.image-height {
		height: 900rpx;
	}

	.image-activity {
		width: 90rpx;
		height: 90rpx;
	}

	.image-small {
		width: 70rpx;
		height: 70rpx;
	}

	.image-small-2 {
		width: 45rpx;
		height: 45rpx;
	}

	.border-left {
		border-left: 1rpx solid #bababa;
	}

	.input-container {
		width: 400rpx;
	}

	.input-style {
		height: 50rpx;
	}

	.fixed-bottom {
		position: fixed;
		left: 0;
		z-index: 999;
		transition: bottom 0.2s ease-in-out;
	}

	button {
		background-color: #ffffff00;
		padding: 0 !important;
		margin: 0 !important;
		line-height: 0rpx !important;
	}

	.img-min {
		top: -60rpx;
		left: 0;
		z-index: 1;
		height: 60rpx;
	}
</style>